package com.sanri.tools.modules.core.service.plugin;



import com.sanri.tools.modules.core.service.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Modifier;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;


/**
 * 类描述 动态加载外部jar包的自定义类加载器
 * @fileName ModuleClassLoader.java
 * @date 2019-06-21 10:22
 * @version 1.0
 *
 */
@Slf4j
public class ModuleClassLoader extends URLClassLoader {

    //属于本类加载器加载的jar包
    private JarFile jarFile;

    //保存已经加载过的Class对象
    private Map<String,Class> cacheClassMap = new HashMap<>();

    //保存本类加载器加载的class字节码
    private Map<String,byte[]> classBytesMap = new HashMap<>();

    /**
     * 注册的 Bean 定义
     */
    private List<String> registeredBean = new ArrayList<>();

    public ModuleClassLoader(File file, ClassLoader parent) throws IOException {
        super(new URL[]{file.toURL()}, parent);
        jarFile = new JarFile(file);
        //初始化类加载器执行类加载
        init();
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        if(findLoadedClass(name)==null){
            return super.loadClass(name);
        }
        return cacheClassMap.get(name);
    }

    /**
      * 方法描述 初始化类加载器，保存字节码
      * @method init
      */
    private void init() throws IOException {
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()){
            JarEntry jarEntry = entries.nextElement();
            String name = jarEntry.getName();
            if (name.endsWith(".class")){
                String className = name.replace(".class", "").replaceAll("/", ".");
                try(InputStream inputStream = jarFile.getInputStream(jarEntry)){
                    final byte[] bytes = IOUtils.toByteArray(inputStream);
                    classBytesMap.put(className,bytes);
                }
            }
        }


        //将jar中的每一个class字节码进行Class载入
        for (Map.Entry<String, byte[]> entry : classBytesMap.entrySet()) {
            String key = entry.getKey();
            Class<?> aClass = null;
            try {
                aClass = loadClass(key);
            } catch (ClassNotFoundException e) {
               log.error("类加载失败: {}",key);
            }
            cacheClassMap.put(key,aClass);
        }

    }

    /**
      * 方法描述 初始化spring bean
      * @method initBean
      */
    public void initBean(){
        for (Map.Entry<String, Class> entry : cacheClassMap.entrySet()) {
            String className = entry.getKey();
            Class<?> cla = entry.getValue();
            if(isSpringBeanClass(cla)){
                BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(cla);
                BeanDefinition beanDefinition = beanDefinitionBuilder.getRawBeanDefinition();
                //设置当前bean定义对象是单利的
                beanDefinition.setScope("singleton");

                //将变量首字母置小写
                String beanWholeName = StringUtils.uncapitalize(className);

                String beanName = FilenameUtils.getExtension(beanWholeName);
                beanName = StringUtils.uncapitalize(beanName);

                SpringUtils.getBeanFactory().registerBeanDefinition(beanName,beanDefinition);
                registeredBean.add(beanName);
                log.info("注册 Bean: {}", beanWholeName);
            }
        }
    }

    //获取当前类加载器注册的bean
    //在移除当前类加载器的时候需要手动删除这些注册的bean
    public List<String> getRegisteredBean() {
        return registeredBean;
    }


    /**
      * 方法描述 判断class对象是否带有spring的注解
      * @method isSpringBeanClass
      * @param cla jar中的每一个class
      * @return true 是spring bean   false 不是spring bean
      */
    public boolean isSpringBeanClass(Class<?> cla){
        if(cla==null){
            return false;
        }
        //是否是接口
        if(cla.isInterface()){
            return false;
        }

        //是否是抽象类
        if( Modifier.isAbstract(cla.getModifiers())){
            return false;
        }

        if(cla.getAnnotation(Component.class)!=null){
            return true;
        }
        if(cla.getAnnotation(Repository.class)!=null){
            return true;
        }
        if(cla.getAnnotation(Service.class)!=null){
            return true;
        }

        return false;
    }

}
